/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package clienteped.NetworkManagerOld;


import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.CharBuffer;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Micosil
 */
public class NetworkReader {

    private BufferedInputStream sin = null;
    private static final int BUFFER_MAX_SIZE = 200;
    private static CharBuffer charBuffer = CharBuffer.allocate(BUFFER_MAX_SIZE);

    public NetworkReader(Socket socket) {

        Logger.getLogger(NetworkReader.class.getName()).addHandler(new ConsoleHandler());
        try {
            sin = new BufferedInputStream(socket.getInputStream());
        } catch (IOException ex) {
            Logger.getLogger(NetworkReader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String readln(){
        return (read() + "\n\r");
    }
    
    public boolean thereAreThingsToRead(){
        try {
            return (sin.available() > 0);
        } catch (IOException ex) {
            Logger.getLogger(NetworkReader.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    public String read(){

        try {
            while ((sin.available() > 0) && (charBuffer.position() < BUFFER_MAX_SIZE)) {
                char readChar = (char) sin.read();                //Habitualmente queremos adelantar por el buffer, a no ser que estemos en el particular caso de manejar un caracter escapado.
                if (elCaracterEstaEscapado(readChar)) {
                    charBuffer.position(charBuffer.position() - 1);
                } else if (readChar == ';') {
                    int finalposition = charBuffer.position();
                    charBuffer.rewind();
                    String toReturn = charBuffer.subSequence(0, finalposition).toString();
                    return (toReturn);
                }
                charBuffer = charBuffer.put(readChar);
            }
            return "";

        } catch (IOException ex) {
            Logger.getGlobal().log(Level.SEVERE, null, ex);            
            return null;
        }
    }

    private boolean elCaracterEstaEscapado(char readChar) {
        return (elCaracterEsEscapable(readChar)) && (charBuffer.position() > 0) && (charBuffer.get(charBuffer.position() - 1) == '/');
    }

    private boolean elCaracterEsEscapable(char readChar) {
        return (readChar == ';');
    }
}
